<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2017/11/11
 * Time: 9:26
 */

namespace app\admin\model;


use think\Db;

class Category extends Admin
{
    public function getKvData()
    {
        return $this->where('status',1)
//            ->where()
            ->column('name','id');
    }

    public function getList( $request )
    {
        $request = $this->fmtRequest( $request );

        $data = $this->alias('s')
                ->join('category p','s.pid = p.id','left')
                ->field('s.id,s.name,p.name as p_name,s.status,s.seo_title,s.seo_keys,s.seo_desc')
                ->limit($request['offset'], $request['limit'])
                ->select();
        return $this->_fmtData($data);
    }
    public function add(array $data = [])
    {
        $CategoryValidate = validate('Category');
        if(!$CategoryValidate->scene('add')->check($data)) {
            return info(lang($CategoryValidate->getError()), 4001);
        }
//        var_dump($data);die;
        $this->allowField(true)->save($data);
        $savedata = Db::name('category')->where('name',$data['name'])->find();
        Db::name('category_desc')->insert(['category_id'=>$savedata['id']]);
        if($this->id > 0){
            return info(lang('Add succeed'), 1, '', $this->id);
        }else{
            return info(lang('Add failed') ,0);
        }
    }

    public function edit(array $data = [])
    {
        $CategoryValidate = validate('Category');
        if(!$CategoryValidate->scene('edit')->check($data)) {
            return info(lang($CategoryValidate->getError()), 4001);
        }

        $res = $this->allowField(true)->save($data,['id'=>$data['id']]);
        if($res == 1){
            return info(lang('Edit succeed'), 1);
        }else{
            return info(lang('Edit failed'), 0);
        }
    }

    public function saveData( $data )
    {
        if( isset( $data['id']) && !empty($data['id'])) {
            $result = $this->edit( $data );
        } else {
            $result = $this->add( $data );
        }
        return $result;
    }

    public function deleteById($id)
    {
        $result = Category::destroy($id);
        if ($result > 0) {
            return info(lang('Delete succeed'), 1);
        }
    }
    private function _fmtData( $data )
    {
        if(empty($data) && is_array($data)) {
            return $data;
        }

        foreach ($data as $key => $value) {

            $data[$key]['status'] = $value['status'] == 1 ? lang('Start') : lang('Off');
        }

        return $data;
    }
}